﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace GameViewer.Core
{
    /** The importance of a logged message.
*/
    public enum LogMessageLevel
    {
        LML_TRIVIAL = 1,
        LML_NORMAL = 2,
        LML_CRITICAL = 3
    };

    public delegate void MessageLogged(string message, LogMessageLevel lml, bool maskDebug, String logName );
   

    public class Log : IDisposable
    {
        private string mLogName;
        private FileStream mStream;
        private StreamWriter mWriter;
        private bool mDebugOut = false;
        private bool mTimeStamp = true;
        private bool mSuppressFile = false;
        List<MessageLogged> mLogListeners = new List<MessageLogged>();

        public Log(string name)
        {
            mLogName = name;

            Initialize();
        }

        public Log(string name, bool debuggerOuput, bool suppressFile)
        {
            mLogName = name;
            mDebugOut = debuggerOuput;
            mSuppressFile = suppressFile;

            Initialize();
        }

        private void Initialize()
        {
            if (!mSuppressFile)
            {
                mStream = new FileStream(mLogName, FileMode.OpenOrCreate);
                mWriter = new StreamWriter(mStream);
            }
        }

        public void LogMessage(string message, LogMessageLevel lml, bool maskDebug)
        {
            foreach (MessageLogged listener in mLogListeners)
            {
                listener.Invoke(message, lml, maskDebug, mLogName);
            }

            if (maskDebug)
            {
                Console.WriteLine(message);
            }
           
            if (!mSuppressFile)
            {
                if (mTimeStamp)
                {
                    message = DateTime.Now.ToLongTimeString() + " " + message;
                }
                mWriter.WriteLine(message);
                mWriter.Flush();
                mStream.Flush();
            }
        }

        public void AddListener(MessageLogged listener)
        {
            mLogListeners.Add(listener);
        }

        public bool TimeStamp
        {
            get
            {
                return mTimeStamp;
            }
            set
            {
                mTimeStamp = value;
            }
        }

        #region IDisposable 成员

        public void Dispose()
        {
            if (!mSuppressFile)
            {
                mWriter.Close();
                mStream.Close();
            }
        }

        #endregion
    }
}
